package top.forgirl.common;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.forgirl.common.result.Result;
import top.forgirl.common.result.ResultType;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

@Component
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 缺少参数的异常
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<String> handlerException(ConstraintViolationException e) {
        return new Result<>(ResultType.PARAM_LACK, e.getLocalizedMessage());
    }

    //validation包异常
    @ExceptionHandler(ValidationException.class)
    public Result<String> handlerValidationException(ValidationException e) {
        return new Result<>(ResultType.VALIDATE, e.getLocalizedMessage());
    }

    //校验参数异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return new Result<>(ResultType.VALIDATE, e.getLocalizedMessage());
    }

    //令牌异常
    @ExceptionHandler(JWTVerificationException.class)
    public Result<String> handlerMethodArgumentNotValidException(JWTVerificationException e) {
        return new Result<>(ResultType.TOKEN_ERROR, e.getLocalizedMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handlerException(Exception e) {
        return new Result<>(ResultType.INTERNAL_ERROR, "未定义错误，如果不影响使用就请继续吧");
    }

}
